package com.demandbreakdown.xiyun.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demandbreakdown.xiyun.common.annotation.OperationLog;
import com.demandbreakdown.xiyun.common.base.ResultCode;
import com.demandbreakdown.xiyun.common.constant.SpaceConstant;
import com.demandbreakdown.xiyun.common.constant.SpaceQuotaConstant;
import com.demandbreakdown.xiyun.common.exception.BusinessException;
import com.demandbreakdown.xiyun.mapper.PictureMapper;
import com.demandbreakdown.xiyun.mapper.SpaceMapper;
import com.demandbreakdown.xiyun.mapper.SpaceUserMapper;
import com.demandbreakdown.xiyun.mapper.UserMapper;
import com.demandbreakdown.xiyun.model.dto.space.*;
import com.demandbreakdown.xiyun.model.entity.Picture;
import com.demandbreakdown.xiyun.model.entity.Space;
import com.demandbreakdown.xiyun.model.entity.SpaceUser;
import com.demandbreakdown.xiyun.model.entity.User;
import com.demandbreakdown.xiyun.model.enums.JoinStatusEnum;
import com.demandbreakdown.xiyun.model.enums.SpaceLevelEnum;
import com.demandbreakdown.xiyun.model.enums.SpaceTypeEnum;
import com.demandbreakdown.xiyun.model.enums.SpaceUserRoleEnum;
import com.demandbreakdown.xiyun.model.vo.space.*;
import com.demandbreakdown.xiyun.model.vo.user.UserVO;
import com.demandbreakdown.xiyun.service.SecurityControlService;
import com.demandbreakdown.xiyun.service.SpaceService;
import com.demandbreakdown.xiyun.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 空间服务实现类
 *
 * @author poxz
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SpaceServiceImpl extends ServiceImpl<SpaceMapper, Space>
        implements SpaceService {

    // Mapper 层依赖
    private final SpaceUserMapper spaceUserMapper;
    private final UserMapper userMapper;
    private final PictureMapper pictureMapper;

    // Service 层依赖
    private final UserService userService;
    private final SecurityControlService securityControlService;

    @Override
    @OperationLog(value = "创建空间", params = {"#userId", "#spaceCreateDTO.spaceName"})
    @Transactional(rollbackFor = Exception.class)
    public SpaceVO createSpace(Long userId, SpaceCreateDTO spaceCreateDTO) {
        // 1. 验证用户是否存在
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException(ResultCode.USER_NOT_FOUND);
        }

        // 2. 验证空间类型
        if (!isValidSpaceType(spaceCreateDTO.getSpaceType())) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "无效的空间类型");
        }

        // 3. 构建空间对象
        Space.SpaceBuilder spaceBuilder = Space.builder()
                .userId(userId)
                .spaceName(spaceCreateDTO.getSpaceName())
                .spaceDesc(spaceCreateDTO.getSpaceDesc())
                .spaceType(spaceCreateDTO.getSpaceType())
                .spaceLevel(SpaceLevelEnum.NORMAL.getValue()) // 默认普通版
                .coverUrl(spaceCreateDTO.getCoverUrl()); // 设置封面图

        // 5. 设置成员上限（仅团队空间需要）
        if (SpaceTypeEnum.TEAM.getValue().equals(spaceCreateDTO.getSpaceType())) {
            if (spaceCreateDTO.getMemberLimit() != null && spaceCreateDTO.getMemberLimit() > 0) {
                int maxMemberLimit = getMaxMemberLimit(SpaceLevelEnum.NORMAL.getValue());
                spaceBuilder.memberLimit(Math.min(spaceCreateDTO.getMemberLimit(), maxMemberLimit));
            }
        }

        Space space = spaceBuilder.build();

        // 4. 设置空间配置
        setSpaceConfig(space, SpaceLevelEnum.NORMAL.getValue());

        // 5. 保存空间
        boolean saved = this.save(space);
        if (!saved) {
            throw new BusinessException(ResultCode.SYSTEM_ERROR, "空间创建失败");
        }

        // 6. 创建者自动成为Owner
        SpaceUser spaceUser = SpaceUser.builder()
                .spaceId(space.getId())
                .userId(userId)
                .userRole(SpaceUserRoleEnum.OWNER.getValue())
                .joinStatus(JoinStatusEnum.JOINED.getValue())
                .joinTime(LocalDateTime.now())
                .build();
        spaceUserMapper.insert(spaceUser);

        // 7. 构建返回结果
        SpaceUsageVO usage = calculateSpaceUsage(space.getId());
        SpaceVO spaceVO = SpaceVO.from(space, SpaceUserRoleEnum.OWNER.getValue(), usage);
        spaceVO.setUser(UserVO.from(user));

        return spaceVO;
    }

    @Override
    public MySpaceVO getMySpaces(Long userId) {
        // 1. 查询用户加入的所有空间
        LambdaQueryWrapper<SpaceUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SpaceUser::getUserId, userId)
                .eq(SpaceUser::getJoinStatus, JoinStatusEnum.JOINED.getValue())
                .orderByDesc(SpaceUser::getJoinTime);

        List<SpaceUser> spaceUsers = spaceUserMapper.selectList(wrapper);
        if (spaceUsers.isEmpty()) {
            return MySpaceVO.builder()
                    .owner(new ArrayList<>())
                    .joined(new ArrayList<>())
                    .build();
        }

        // 2. 获取空间信息
        List<Long> spaceIds = spaceUsers.stream()
                .map(SpaceUser::getSpaceId)
                .collect(Collectors.toList());

        List<Space> spaces = this.listByIds(spaceIds);
        Map<Long, Space> spaceMap = spaces.stream()
                .collect(Collectors.toMap(Space::getId, s -> s));

        // 3. 获取创建者信息
        List<Long> userIds = spaces.stream()
                .map(Space::getUserId)
                .distinct()
                .collect(Collectors.toList());

        List<User> users = userService.listByIds(userIds);
        Map<Long, User> userMap = users.stream()
                .collect(Collectors.toMap(User::getId, u -> u));

        // 4. 构建返回结果
        List<SpaceVO> ownerSpaces = new ArrayList<>();
        List<SpaceVO> joinedSpaces = new ArrayList<>();

        for (SpaceUser spaceUser : spaceUsers) {
            Space space = spaceMap.get(spaceUser.getSpaceId());
            if (space == null) continue;

            User creator = userMap.get(space.getUserId());
            SpaceUsageVO usage = calculateSpaceUsage(space.getId());
            SpaceVO spaceVO = SpaceVO.from(space, spaceUser.getUserRole(), usage);

            if (creator != null) {
                spaceVO.setUser(UserVO.from(creator));
            }

            if (SpaceUserRoleEnum.OWNER.getValue().equals(spaceUser.getUserRole())) {
                ownerSpaces.add(spaceVO);
            } else {
                joinedSpaces.add(spaceVO);
            }
        }

        return MySpaceVO.builder()
                .owner(ownerSpaces)
                .joined(joinedSpaces)
                .build();
    }

    @Override
    public SpaceVO getSpaceById(Long spaceId, Long userId) {
        // 1. 查询空间
        Space space = this.getById(spaceId);
        if (space == null) {
            throw new BusinessException(ResultCode.SPACE_NOT_FOUND, "空间不存在");
        }

        // 2. 验证访问权限
        String userRole = validateSpaceAccess(spaceId, userId);

        // 3. 获取创建者信息
        User creator = userMapper.selectById(space.getUserId());

        // 4. 计算使用情况
        SpaceUsageVO usage = calculateSpaceUsage(spaceId);

        // 5. 构建返回结果
        SpaceVO spaceVO = SpaceVO.from(space, userRole, usage);
        if (creator != null) {
            spaceVO.setUser(UserVO.from(creator));
        }

        return spaceVO;
    }

    @Override
    @OperationLog("更新空间信息")
    @Transactional(rollbackFor = Exception.class)
    public SpaceVO updateSpace(Long spaceId, Long userId, SpaceUpdateDTO spaceUpdateDTO) {
        // 1. 查询空间
        Space space = this.getById(spaceId);
        if (space == null) {
            throw new BusinessException(ResultCode.SPACE_NOT_FOUND, "空间不存在");
        }

        // 2. 验证权限（只有Owner可以更新）
        validateSpaceOwner(spaceId, userId);

        // 3. 更新信息
        if (StrUtil.isNotBlank(spaceUpdateDTO.getSpaceName())) {
            space.setSpaceName(spaceUpdateDTO.getSpaceName());
        }
        if (spaceUpdateDTO.getSpaceDesc() != null) {
            space.setSpaceDesc(spaceUpdateDTO.getSpaceDesc());
        }
        if (StrUtil.isNotBlank(spaceUpdateDTO.getCoverUrl())) {
            space.setCoverUrl(spaceUpdateDTO.getCoverUrl());
        }
        // 只有团队空间才能修改成员上限
        if (SpaceTypeEnum.TEAM.getValue().equals(space.getSpaceType()) && spaceUpdateDTO.getMemberLimit() != null && spaceUpdateDTO.getMemberLimit() > 0) {
            int maxMemberLimit = getMaxMemberLimit(space.getSpaceLevel());
            space.setMemberLimit(Math.min(spaceUpdateDTO.getMemberLimit(), maxMemberLimit));
        }

        // 4. 保存更新
        boolean updated = this.updateById(space);
        if (!updated) {
            throw new BusinessException(ResultCode.SYSTEM_ERROR, "空间更新失败");
        }

        // 5. 构建返回结果
        SpaceUsageVO usage = calculateSpaceUsage(spaceId);
        SpaceVO spaceVO = SpaceVO.from(space, SpaceUserRoleEnum.OWNER.getValue(), usage);

        User creator = userMapper.selectById(space.getUserId());
        if (creator != null) {
            spaceVO.setUser(UserVO.from(creator));
        }

        return spaceVO;
    }

    @Override
    @OperationLog(value = "升级空间", params = {"#spaceId", "#userId", "#spaceUpgradeDTO.spaceLevel"})
    @Transactional(rollbackFor = Exception.class)
    public SpaceVO upgradeSpace(Long spaceId, Long userId, SpaceUpgradeDTO spaceUpgradeDTO) {
        // 1. 查询空间
        Space space = this.getById(spaceId);
        if (space == null) {
            throw new BusinessException(ResultCode.SPACE_NOT_FOUND, "空间不存在");
        }

        // 2. 验证权限（只有Owner可以升级）
        validateSpaceOwner(spaceId, userId);

        // 3. 验证升级级别
        if (spaceUpgradeDTO.getSpaceLevel() <= space.getSpaceLevel()) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "只能升级到更高级别");
        }

        if (!isValidSpaceLevel(spaceUpgradeDTO.getSpaceLevel())) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "无效的空间级别");
        }

        // 4. 更新空间级别和配置
        space.setSpaceLevel(spaceUpgradeDTO.getSpaceLevel());
        setSpaceConfig(space, spaceUpgradeDTO.getSpaceLevel());

        // 5. 保存更新
        boolean updated = this.updateById(space);
        if (!updated) {
            throw new BusinessException(ResultCode.SYSTEM_ERROR, "空间升级失败");
        }

        // 6. 构建返回结果
        SpaceUsageVO usage = calculateSpaceUsage(spaceId);
        SpaceVO spaceVO = SpaceVO.from(space, SpaceUserRoleEnum.OWNER.getValue(), usage);

        User creator = userMapper.selectById(space.getUserId());
        if (creator != null) {
            spaceVO.setUser(UserVO.from(creator));
        }

        return spaceVO;
    }

    @Override
    @OperationLog("生成邀请码")
    @Transactional(rollbackFor = Exception.class)
    public SpaceInviteVO generateInviteCode(Long spaceId, Long userId) {
        // 1. 查询空间
        Space space = this.getById(spaceId);
        if (space == null) {
            throw new BusinessException(ResultCode.SPACE_NOT_FOUND, "空间不存在");
        }

        // 2. 验证权限（Owner和Editor可以生成邀请码）
        String userRole = validateSpaceAccess(spaceId, userId);
        if (!SpaceUserRoleEnum.OWNER.getValue().equals(userRole) &&
                !SpaceUserRoleEnum.EDITOR.getValue().equals(userRole)) {
            throw new BusinessException(ResultCode.USER_NO_PERMISSION, "只有空间所有者和编辑者可以生成邀请码");
        }

        // 3. 生成新的邀请码
        String inviteCode = generateUniqueInviteCode();
        space.setInviteCode(inviteCode);

        // 4. 保存更新
        boolean updated = this.updateById(space);
        if (!updated) {
            throw new BusinessException(ResultCode.SYSTEM_ERROR, "邀请码生成失败");
        }

        return SpaceInviteVO.builder()
                .inviteCode(inviteCode)
                .build();
    }

    @Override
    @OperationLog(value = "加入空间", params = {"#userId", "#spaceJoinDTO.inviteCode"})
    @Transactional(rollbackFor = Exception.class)
    public SpaceVO joinSpace(Long userId, SpaceJoinDTO spaceJoinDTO) {
        // 1. 通过邀请码查询空间
        LambdaQueryWrapper<Space> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Space::getInviteCode, spaceJoinDTO.getInviteCode());
        Space space = this.getOne(wrapper);

        if (space == null) {
            throw new BusinessException(ResultCode.SPACE_INVITE_CODE_INVALID, "邀请码无效");
        }

        // 2. 检查邀请码是否过期（72小时有效期）
        if (securityControlService.isInviteCodeExpired(space.getId(), spaceJoinDTO.getInviteCode())) {
            throw new BusinessException(ResultCode.SPACE_INVITE_CODE_INVALID, "邀请码已过期，请联系空间管理员重新生成");
        }

        // 3. 检查是否已经是成员
        LambdaQueryWrapper<SpaceUser> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(SpaceUser::getSpaceId, space.getId())
                .eq(SpaceUser::getUserId, userId);
        SpaceUser existingUser = spaceUserMapper.selectOne(userWrapper);

        if (existingUser != null) {
            if (JoinStatusEnum.JOINED.getValue().equals(existingUser.getJoinStatus())) {
                throw new BusinessException(ResultCode.PARAMS_ERROR, "您已经是该空间的成员");
            }
            // 更新状态为已加入
            existingUser.setJoinStatus(JoinStatusEnum.JOINED.getValue());
            existingUser.setJoinTime(LocalDateTime.now());
            spaceUserMapper.updateById(existingUser);
        } else {
            // 4. 检查成员数量限制（仅团队空间需要检查）
            if (SpaceTypeEnum.TEAM.getValue().equals(space.getSpaceType()) && space.getMemberLimit() != null) {
                long currentMemberCount = getCurrentMemberCount(space.getId());
                if (currentMemberCount >= space.getMemberLimit()) {
                    throw new BusinessException(ResultCode.SPACE_MEMBER_LIMIT, "空间成员已达上限");
                }
            }

            // 5. 添加新成员
            SpaceUser spaceUser = SpaceUser.builder()
                    .spaceId(space.getId())
                    .userId(userId)
                    .userRole(SpaceUserRoleEnum.VIEWER.getValue()) // 默认为查看者
                    .joinStatus(JoinStatusEnum.JOINED.getValue())
                    .joinTime(LocalDateTime.now())
                    .build();
            spaceUserMapper.insert(spaceUser);
        }

        // 6. 构建返回结果
        SpaceUsageVO usage = calculateSpaceUsage(space.getId());
        SpaceVO spaceVO = SpaceVO.from(space, SpaceUserRoleEnum.VIEWER.getValue(), usage);

        User creator = userMapper.selectById(space.getUserId());
        if (creator != null) {
            spaceVO.setUser(UserVO.from(creator));
        }

        return spaceVO;
    }

    @Override
    public SpaceUserListVO getSpaceMembers(Long spaceId, Long userId) {
        // 1. 验证访问权限
        validateSpaceAccess(spaceId, userId);

        // 2. 查询空间成员
        LambdaQueryWrapper<SpaceUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SpaceUser::getSpaceId, spaceId)
                .eq(SpaceUser::getJoinStatus, JoinStatusEnum.JOINED.getValue())
                .orderByAsc(SpaceUser::getUserRole)
                .orderByAsc(SpaceUser::getJoinTime);

        List<SpaceUser> spaceUsers = spaceUserMapper.selectList(wrapper);
        if (spaceUsers.isEmpty()) {
            return SpaceUserListVO.builder()
                    .total(0)
                    .list(new ArrayList<>())
                    .build();
        }

        // 3. 获取用户信息
        List<Long> userIds = spaceUsers.stream()
                .map(SpaceUser::getUserId)
                .collect(Collectors.toList());

        List<User> users = userService.listByIds(userIds);
        Map<Long, User> userMap = users.stream()
                .collect(Collectors.toMap(User::getId, u -> u));

        // 4. 构建返回结果
        List<SpaceUserVO> memberList = spaceUsers.stream()
                .map(spaceUser -> {
                    User user = userMap.get(spaceUser.getUserId());
                    return SpaceUserVO.from(spaceUser, user != null ? UserVO.from(user) : null);
                })
                .collect(Collectors.toList());

        return SpaceUserListVO.builder()
                .total(memberList.size())
                .list(memberList)
                .build();
    }

    @Override
    @OperationLog(value = "更新成员角色", params = {"#spaceId", "#currentUserId", "#targetUserId", "#roleUpdateDTO.userRole"})
    @Transactional(rollbackFor = Exception.class)
    public void updateMemberRole(Long spaceId, Long currentUserId, Long targetUserId, SpaceUserRoleUpdateDTO roleUpdateDTO) {
        // 1. 验证权限（只有Owner可以修改角色）
        validateSpaceOwner(spaceId, currentUserId);

        // 2. 不能修改自己的角色
        if (currentUserId.equals(targetUserId)) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "不能修改自己的角色");
        }

        // 3. 查询目标用户
        LambdaQueryWrapper<SpaceUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SpaceUser::getSpaceId, spaceId)
                .eq(SpaceUser::getUserId, targetUserId)
                .eq(SpaceUser::getJoinStatus, JoinStatusEnum.JOINED.getValue());

        SpaceUser spaceUser = spaceUserMapper.selectOne(wrapper);
        if (spaceUser == null) {
            throw new BusinessException(ResultCode.NOT_FOUND, "用户不是该空间的成员");
        }

        // 4. 验证新角色
        if (!isValidUserRole(roleUpdateDTO.getUserRole())) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "无效的用户角色");
        }

        // 5. 不能将成员设置为Owner
        if (SpaceUserRoleEnum.OWNER.getValue().equals(roleUpdateDTO.getUserRole())) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "不能将成员设置为所有者，请使用转让功能");
        }

        // 6. 更新角色
        spaceUser.setUserRole(roleUpdateDTO.getUserRole());
        boolean updated = spaceUserMapper.updateById(spaceUser) > 0;
        if (!updated) {
            throw new BusinessException(ResultCode.SYSTEM_ERROR, "角色更新失败");
        }
    }

    @Override
    @OperationLog(value = "踢出成员", bizType = "空间管理")
    @Transactional(rollbackFor = Exception.class)
    public void removeMember(Long spaceId, Long currentUserId, Long targetUserId) {
        // 1. 验证权限（只有Owner可以踢出成员）
        validateSpaceOwner(spaceId, currentUserId);

        // 2. 不能踢出自己
        if (currentUserId.equals(targetUserId)) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "不能踢出自己");
        }

        // 3. 查询目标用户
        LambdaQueryWrapper<SpaceUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SpaceUser::getSpaceId, spaceId)
                .eq(SpaceUser::getUserId, targetUserId)
                .eq(SpaceUser::getJoinStatus, JoinStatusEnum.JOINED.getValue());

        SpaceUser spaceUser = spaceUserMapper.selectOne(wrapper);
        if (spaceUser == null) {
            throw new BusinessException(ResultCode.NOT_FOUND, "用户不是该空间的成员");
        }

        // 4. 删除成员
        boolean removed = spaceUserMapper.deleteById(spaceUser.getId()) > 0;
        if (!removed) {
            throw new BusinessException(ResultCode.SYSTEM_ERROR, "踢出成员失败");
        }
    }

    @Override
    @OperationLog(value = "转让空间", bizType = "空间管理")
    @Transactional(rollbackFor = Exception.class)
    public void transferSpace(Long spaceId, Long currentUserId, SpaceTransferDTO spaceTransferDTO) {
        // 1. 验证权限（只有Owner可以转让）
        validateSpaceOwner(spaceId, currentUserId);

        // 2. 不能转让给自己
        if (currentUserId.equals(spaceTransferDTO.getNewOwnerUserId())) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "不能转让给自己");
        }

        // 3. 查询新Owner
        LambdaQueryWrapper<SpaceUser> newOwnerWrapper = new LambdaQueryWrapper<>();
        newOwnerWrapper.eq(SpaceUser::getSpaceId, spaceId)
                .eq(SpaceUser::getUserId, spaceTransferDTO.getNewOwnerUserId())
                .eq(SpaceUser::getJoinStatus, JoinStatusEnum.JOINED.getValue());

        SpaceUser newOwner = spaceUserMapper.selectOne(newOwnerWrapper);
        if (newOwner == null) {
            throw new BusinessException(ResultCode.NOT_FOUND, "目标用户不是该空间的成员");
        }

        // 4. 查询当前Owner
        LambdaQueryWrapper<SpaceUser> currentOwnerWrapper = new LambdaQueryWrapper<>();
        currentOwnerWrapper.eq(SpaceUser::getSpaceId, spaceId)
                .eq(SpaceUser::getUserId, currentUserId)
                .eq(SpaceUser::getUserRole, SpaceUserRoleEnum.OWNER.getValue());

        SpaceUser currentOwner = spaceUserMapper.selectOne(currentOwnerWrapper);
        if (currentOwner == null) {
            throw new BusinessException(ResultCode.USER_NO_PERMISSION, "您不是该空间的所有者");
        }

        // 5. 更新空间所有者
        Space space = this.getById(spaceId);
        space.setUserId(spaceTransferDTO.getNewOwnerUserId());
        this.updateById(space);

        // 6. 更新用户角色
        newOwner.setUserRole(SpaceUserRoleEnum.OWNER.getValue());
        currentOwner.setUserRole(SpaceUserRoleEnum.EDITOR.getValue());

        spaceUserMapper.updateById(newOwner);
        spaceUserMapper.updateById(currentOwner);
    }

    /**
     * 验证空间访问权限
     */
    private String validateSpaceAccess(Long spaceId, Long userId) {
        LambdaQueryWrapper<SpaceUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SpaceUser::getSpaceId, spaceId)
                .eq(SpaceUser::getUserId, userId)
                .eq(SpaceUser::getJoinStatus, JoinStatusEnum.JOINED.getValue());

        SpaceUser spaceUser = spaceUserMapper.selectOne(wrapper);
        if (spaceUser == null) {
            throw new BusinessException(ResultCode.USER_NO_PERMISSION, "无权限访问此空间");
        }

        return spaceUser.getUserRole();
    }

    /**
     * 验证空间所有者权限
     */
    private void validateSpaceOwner(Long spaceId, Long userId) {
        String userRole = validateSpaceAccess(spaceId, userId);
        if (!SpaceUserRoleEnum.OWNER.getValue().equals(userRole)) {
            throw new BusinessException(ResultCode.USER_NO_PERMISSION, "只有空间所有者可以执行此操作");
        }
    }

    /**
     * 计算空间使用情况
     */
    private SpaceUsageVO calculateSpaceUsage(Long spaceId) {
        // 统计图片数量和存储大小
        LambdaQueryWrapper<Picture> pictureWrapper = new LambdaQueryWrapper<>();
        pictureWrapper.eq(Picture::getSpaceId, spaceId);
        List<Picture> pictures = pictureMapper.selectList(pictureWrapper);

        int pictureCount = pictures.size();
        long storageSize = pictures.stream()
                .mapToLong(Picture::getFileSize)
                .sum();

        // 统计成员数量
        int memberCount = (int) getCurrentMemberCount(spaceId);

        return SpaceUsageVO.builder()
                .currentPictureCount(pictureCount)
                .currentStorageSize(storageSize)
                .currentMemberCount(memberCount)
                .build();
    }

    /**
     * 获取当前成员数量
     */
    private long getCurrentMemberCount(Long spaceId) {
        LambdaQueryWrapper<SpaceUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SpaceUser::getSpaceId, spaceId)
                .eq(SpaceUser::getJoinStatus, JoinStatusEnum.JOINED.getValue());
        return spaceUserMapper.selectCount(wrapper);
    }

    /**
     * 设置空间配置
     */
    private void setSpaceConfig(Space space, Integer spaceLevel) {
        switch (spaceLevel) {
            case 0 -> { // 普通版
                space.setMaxPictureCount(SpaceQuotaConstant.NORMAL_MAX_PICTURES);
                space.setMaxStorageSize(SpaceQuotaConstant.NORMAL_MAX_STORAGE);
                // 只有团队空间才设置成员上限
                if (SpaceTypeEnum.TEAM.getValue().equals(space.getSpaceType()) && space.getMemberLimit() == null) {
                    space.setMemberLimit(SpaceQuotaConstant.NORMAL_MAX_MEMBERS);
                }
            }
            case 1 -> { // 高级版
                space.setMaxPictureCount(SpaceQuotaConstant.ADVANCED_MAX_PICTURES);
                space.setMaxStorageSize(SpaceQuotaConstant.ADVANCED_MAX_STORAGE);
                // 只有团队空间才设置成员上限
                if (SpaceTypeEnum.TEAM.getValue().equals(space.getSpaceType()) && space.getMemberLimit() == null) {
                    space.setMemberLimit(SpaceQuotaConstant.ADVANCED_MAX_MEMBERS);
                }
            }
            case 2 -> { // 至尊版
                space.setMaxPictureCount(SpaceQuotaConstant.PREMIUM_MAX_PICTURES);
                space.setMaxStorageSize(SpaceQuotaConstant.PREMIUM_MAX_STORAGE);
                // 只有团队空间才设置成员上限
                if (SpaceTypeEnum.TEAM.getValue().equals(space.getSpaceType()) && space.getMemberLimit() == null) {
                    space.setMemberLimit(SpaceQuotaConstant.PREMIUM_MAX_MEMBERS);
                }
            }
            default -> throw new BusinessException(ResultCode.PARAMS_ERROR, "无效的空间级别");
        }
    }

    /**
     * 获取最大成员限制
     */
    private int getMaxMemberLimit(Integer spaceLevel) {
        return switch (spaceLevel) {
            case 0 -> SpaceQuotaConstant.NORMAL_MAX_MEMBERS;
            case 1 -> SpaceQuotaConstant.ADVANCED_MAX_MEMBERS;
            case 2 -> SpaceQuotaConstant.PREMIUM_MAX_MEMBERS;
            default -> SpaceQuotaConstant.NORMAL_MAX_MEMBERS;
        };
    }

    /**
     * 生成唯一邀请码
     */
    private String generateUniqueInviteCode() {
        String inviteCode;
        int attempts = 0;
        do {
            inviteCode = RandomUtil.randomString(SpaceConstant.INVITE_CODE_LENGTH).toUpperCase();
            attempts++;
            if (attempts > SpaceConstant.INVITE_CODE_MAX_ATTEMPTS) {
                throw new BusinessException(ResultCode.SYSTEM_ERROR);
            }
        } while (isInviteCodeExists(inviteCode));
        return inviteCode;
    }

    /**
     * 检查邀请码是否存在
     */
    private boolean isInviteCodeExists(String inviteCode) {
        LambdaQueryWrapper<Space> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Space::getInviteCode, inviteCode);
        return this.count(wrapper) > 0;
    }

    /**
     * 验证空间类型
     */
    private boolean isValidSpaceType(Integer spaceType) {
        return spaceType != null &&
                (SpaceTypeEnum.PRIVATE.getValue().equals(spaceType) ||
                        SpaceTypeEnum.TEAM.getValue().equals(spaceType));
    }

    /**
     * 验证空间级别
     */
    private boolean isValidSpaceLevel(Integer spaceLevel) {
        return spaceLevel != null &&
                (SpaceLevelEnum.NORMAL.getValue().equals(spaceLevel) ||
                        SpaceLevelEnum.ADVANCED.getValue().equals(spaceLevel) ||
                        SpaceLevelEnum.PREMIUM.getValue().equals(spaceLevel));
    }

    /**
     * 验证用户角色
     */
    private boolean isValidUserRole(String userRole) {
        return SpaceUserRoleEnum.OWNER.getValue().equals(userRole) ||
                SpaceUserRoleEnum.EDITOR.getValue().equals(userRole) ||
                SpaceUserRoleEnum.VIEWER.getValue().equals(userRole);
    }

    @Override
    @OperationLog(value = "删除空间", bizType = "空间管理")
    @Transactional(rollbackFor = Exception.class)
    public void deleteSpace(Long spaceId, Long userId) {
        // 1. 查询空间是否存在
        Space space = this.getById(spaceId);
        if (space == null) {
            throw new BusinessException(ResultCode.SPACE_NOT_FOUND, "空间不存在");
        }

        // 2. 验证权限（只有Owner可以删除空间）
        validateSpaceOwner(spaceId, userId);

        // 3. 禁止删除私人空间
        if (SpaceTypeEnum.PRIVATE.getValue().equals(space.getSpaceType())) {
            throw new BusinessException(ResultCode.PARAMS_ERROR);
        }

        // 3. 级联删除相关数据
        try {
            // 3.1 删除空间内的图片（软删除）
            deleteSpacePictures(spaceId);

            // 3.2 删除空间成员关系
            deleteSpaceMembers(spaceId);

            // 3.3 删除空间本身
            boolean deleted = this.removeById(spaceId);
            if (!deleted) {
                throw new BusinessException(ResultCode.SYSTEM_ERROR, "空间删除失败");
            }

        } catch (Exception e) {
            log.error("空间删除失败: spaceId={}, userId={}, error={}", spaceId, userId, e.getMessage());
            throw new BusinessException(ResultCode.SYSTEM_ERROR, "空间删除失败: " + e.getMessage());
        }
    }

    /**
     * 删除空间内的所有图片（软删除）
     */
    private void deleteSpacePictures(Long spaceId) {
        try {
            LambdaQueryWrapper<Picture> pictureWrapper = new LambdaQueryWrapper<>();
            pictureWrapper.eq(Picture::getSpaceId, spaceId);

            // 先获取图片数量
            long pictureCount = pictureMapper.selectCount(pictureWrapper);

            if (pictureCount > 0) {
                // 批量软删除图片 - 使用SQL批量更新提高性能
                LambdaUpdateWrapper<Picture> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(Picture::getSpaceId, spaceId)
                        .set(Picture::getIsDelete, 1);

                int updatedCount = pictureMapper.update(null, updateWrapper);

                log.info("空间图片删除完成: spaceId={}, count={}", spaceId, updatedCount);
            } else {
                log.info("空间无图片需要删除: spaceId={}", spaceId);
            }

        } catch (Exception e) {
            log.error("删除空间图片失败: spaceId={}, error={}", spaceId, e.getMessage());
            throw e;
        }
    }

    /**
     * 删除空间的所有成员关系
     */
    private void deleteSpaceMembers(Long spaceId) {
        try {
            LambdaQueryWrapper<SpaceUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SpaceUser::getSpaceId, spaceId);

            int memberCount = Math.toIntExact(spaceUserMapper.selectCount(wrapper));

            if (memberCount > 0) {
                spaceUserMapper.delete(wrapper);
                log.info("空间成员关系删除完成: spaceId={}, count={}", spaceId, memberCount);
            }

        } catch (Exception e) {
            log.error("删除空间成员关系失败: spaceId={}, error={}", spaceId, e.getMessage());
            throw e;
        }
    }
}